<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能体对话系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 替换为 markdown-it -->
    <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/markdown-it-task-lists@2.1.1/dist/markdown-it-task-lists.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dompurify@2.4.0/dist/purify.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Highlight.js 代码高亮支持 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/languages/python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/languages/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/languages/json.min.js"></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

        :root {
            --user-bg: linear-gradient(135deg, #3498db, #1a75bc);
            --ai-bg: rgba(255, 255, 255, 0.93);
            --primary: #1e88e5;
            --dark-bg: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
            --sidebar-bg: rgba(15, 32, 39, 0.95);
            --error-bg: linear-gradient(135deg, #e53935, #c62828);
            --code-bg: #1e1e1e;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--dark-bg);
            height: 100vh;
            overflow: hidden;
            color: #2d3748;
        }

        .message-container {
            scroll-behavior: smooth;
        }

        .message-container::-webkit-scrollbar {
            width: 8px;
        }

        .message-container::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
        }

        .message-container::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
        }

        .user-message {
            border-radius: 18px 4px 18px 18px;
            background: var(--user-bg);
            color: white;
            max-width: 80%;
            align-self: flex-end;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
        }

        .ai-message {
            border-radius: 4px 18px 18px 18px;
            background: var(--ai-bg);
            max-width: 80%;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            position: relative;
        }

        .error-message {
            border-radius: 4px 18px 18px 18px;
            background: var(--error-bg);
            color: white;
            max-width: 80%;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(229, 57, 53, 0.2);
        }

        .ai-message:before {
            content: "";
            position: absolute;
            left: -12px;
            top: 20px;
            border: 8px solid transparent;
            border-right-color: var(--ai-bg);
        }

        .typing-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: var(--primary);
            margin: 0 4px;
            opacity: 0.6;
        }

        .chat-input:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
        }

        .send-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        }

        .progress-bar {
            height: 4px;
            background: var(--user-bg);
            width: 0%;
            transition: width 0.3s ease;
        }

        .message-content {
            max-height: 300px;
            overflow-y: auto;
            padding-right: 8px;
        }

        .message-content::-webkit-scrollbar {
            width: 6px;
        }

        .message-content::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.05);
            border-radius: 10px;
        }

        .message-content::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.15);
            border-radius: 10px;
        }

        .user-message .message-content::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
        }

        .user-message .message-content::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
        }

        .avatar {
            flex-shrink: 0;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .step-badge {
            position: absolute;
            top: -12px;
            left: 15px;
            background: linear-gradient(135deg, #3498db, #1a75bc);
            color: white;
            font-size: 12px;
            font-weight: 600;
            padding: 3px 10px;
            border-radius: 12px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .pulse {
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
                opacity: 1;
            }
            50% {
                transform: scale(1.05);
                opacity: 0.9;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .task-indicator {
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 20px;
            padding: 5px 15px;
            margin-bottom: 10px;
            font-size: 14px;
            color: white;
        }

        /* 会话侧边栏样式 */
        .sidebar {
            background: var(--sidebar-bg);
            backdrop-filter: blur(10px);
            width: 280px;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            height: 100vh;
            overflow-y: auto;
            transition: transform 0.3s ease;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .session-item {
            padding: 12px 16px;
            border-radius: 8px;
            margin: 6px 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }

        .session-item:hover {
            background: rgba(255, 255, 255, 0.08);
        }

        .session-item.active {
            background: rgba(41, 121, 255, 0.2);
            border-left: 3px solid #2979ff;
        }

        .session-item.active .session-title {
            color: white;
        }

        .session-title {
            font-weight: 500;
            color: rgba(255, 255, 255, 0.8);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .session-time {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.5);
            margin-top: 4px;
        }

        .sidebar-footer {
            padding: 16px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .new-session-btn {
            background: linear-gradient(135deg, #3498db, #1a75bc);
            color: white;
            border-radius: 8px;
            padding: 12px;
            text-align: center;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .new-session-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        }

        .main-content {
            flex: 1;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .session-header {
            background: rgba(15, 32, 39, 0.95);
            padding: 16px 24px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .menu-toggle {
            display: none;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 8px;
            cursor: pointer;
        }

        @media (max-width: 768px) {
            .sidebar {
                position: absolute;
                transform: translateX(-100%);
                z-index: 100;
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .menu-toggle {
                display: block;
            }

            .session-item {
                margin: 6px 8px;
            }
        }

        .session-title-input {
            background: transparent;
            border: none;
            color: white;
            font-size: 18px;
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 4px;
            width: 100%;
            max-width: 400px;
        }

        .session-title-input:focus {
            outline: none;
            background: rgba(255, 255, 255, 0.1);
        }

        .session-actions button {
            background: rgba(255, 255, 255, 0.1);
            border: none;
            border-radius: 6px;
            padding: 6px 12px;
            color: rgba(255, 255, 255, 0.8);
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .session-actions button:hover {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }

        .connection-status {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            z-index: 50;
        }

        .connected {
            background: rgba(46, 204, 113, 0.9);
            color: white;
        }

        .disconnected {
            background: rgba(231, 76, 60, 0.9);
            color: white;
        }

        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        /* 代码块高亮样式 */
        pre {
            position: relative;
            background-color: var(--code-bg) !important;
            border-radius: 8px;
            padding: 20px 15px 15px 15px !important;
            overflow-x: auto;
            font-size: 14px;
            margin: 15px 0;
        }

        pre code {
            padding: 0 !important;
            background: none !important;
        }

        .copy-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .copy-btn:hover {
            background: rgba(255, 255, 255, 0.25);
        }

        /* 消息折叠/展开样式 */
        .collapsible-message {
            max-height: 150px;
            overflow: hidden;
            position: relative;
            transition: max-height 0.3s ease;
        }

        .collapsed .collapsible-message {
            max-height: 150px;
        }

        .expanded .collapsible-message {
            max-height: 2000px;
        }

        .collapsible-message::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 40px;
            background: linear-gradient(to bottom, transparent, var(--ai-bg));
            display: none;
        }

        .collapsed .collapsible-message::after {
            display: block;
        }

        .expand-btn {
            background: rgba(52, 152, 219, 0.15);
            color: #1a75bc;
            border: none;
            border-radius: 20px;
            padding: 6px 12px;
            font-size: 12px;
            cursor: pointer;
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 4px;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        .expand-btn:hover {
            background: rgba(52, 152, 219, 0.25);
        }

        .expand-btn .expanded {
            display: none;
        }

        .expanded .expand-btn .expanded {
            display: inline;
        }

        .expanded .expand-btn .collapsed {
            display: none;
        }

        /* Markdown表格样式 */
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 15px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        th, td {
            border: 1px solid #e2e8f0;
            padding: 8px 12px;
            text-align: left;
        }

        th {
            background-color: #f7fafc;
            font-weight: 600;
        }

        tr:nth-child(even) {
            background-color: #f8fafc;
        }

        /* 列表样式 */
        ul, ol {
            padding-left: 20px;
            margin: 10px 0;
        }

        li {
            margin-bottom: 6px;
            line-height: 1.6;
        }

        /* 引用样式 */
        blockquote {
            border-left: 4px solid #3498db;
            padding: 8px 15px;
            margin: 15px 0;
            background: rgba(52, 152, 219, 0.05);
            border-radius: 0 8px 8px 0;
            font-style: italic;
        }

        /* 消息类型标签 */
        .message-label {
            font-size: 12px;
            font-weight: 600;
            padding: 2px 8px;
            border-radius: 4px;
            background: rgba(0, 0, 0, 0.1);
            display: inline-block;
            margin-bottom: 8px;
        }

        /* 新增：响应式表格容器 */
        .table-responsive {
            display: block;
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
    </style>
</head>

<body class="flex h-screen text-gray-800">
<!-- 连接状态指示器 -->
<div id="connection-status" class="connection-status connected">
    <div class="status-indicator bg-white"></div>
    <span>已连接到SSE服务</span>
</div>

<!-- 会话侧边栏 -->
<div id="sidebar" class="sidebar">
    <div class="sidebar-header">
        <div class="flex items-center space-x-3">
            <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                <i class="fas fa-robot text-white text-xl"></i>
            </div>
            <h2 class="text-xl font-bold text-white">AI会话管理</h2>
        </div>
    </div>

    <div id="sessions-list" class="py-3">
        <!-- 会话列表将通过JS动态生成 -->
    </div>

    <div class="sidebar-footer">
        <div id="new-session-btn" class="new-session-btn">
            <i class="fas fa-plus mr-2"></i>创建新会话
        </div>
    </div>
</div>

<!-- 主内容区域 -->
<div class="main-content">
    <!-- 顶部导航栏 -->
    <div class="session-header">
        <div class="flex items-center">
            <div id="menu-toggle" class="menu-toggle mr-3">
                <i class="fas fa-bars text-white"></i>
            </div>
            <input id="session-title-input" class="session-title-input" type="text" placeholder="会话标题">
        </div>
        <div class="session-actions">
            <button id="clear-chat-btn">
                <i class="fas fa-trash-alt mr-1"></i>清空对话
            </button>
        </div>
    </div>

    <!-- 进度条 -->
    <div class="progress-bar"></div>

    <!-- 对话内容区域 -->
    <main class="flex-1 overflow-hidden py-4 px-4">
        <div class="h-full flex flex-col">
            <div id="chat-container" class="message-container flex-1 overflow-y-auto py-2 space-y-6 px-2">
                <!-- 初始欢迎消息 -->
                <div class="flex justify-start">
                    <div class="ai-message p-5">
                        <div class="flex items-start space-x-4">
                            <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                                <i class="fas fa-robot text-white text-lg"></i>
                            </div>
                            <div class="flex-1">
                                <div class="task-indicator">
                                    <i class="fas fa-info-circle mr-2"></i>
                                    系统初始化完成，随时为您服务
                                </div>
                                <div class="prose prose-blue max-w-none message-content">
                                    <p>您好！我是您的AI助手，随时准备为您服务。</p>
                                    <p>您可以向我提出各种问题或任务，例如：</p>
                                    <ul>
                                        <li>撰写一篇关于人工智能的短文</li>
                                        <li>解释量子计算的基本概念</li>
                                        <li>制定一个健身计划</li>
                                        <li>编写一段Python代码</li>
                                    </ul>
                                    <p>请在下方的输入框中描述您的需求，我会尽快为您处理！</p>

                                    <p class="mt-4"><strong>新功能说明：</strong></p>
                                    <ul>
                                        <li>支持完整的Markdown渲染</li>
                                        <li>代码块高亮显示</li>
                                        <li>一键复制代码功能</li>
                                        <li>长消息折叠/展开功能</li>
                                        <li>任务状态管理优化</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="mt-4 bg-white rounded-xl shadow-lg p-4">
                <div class="flex space-x-3">
                    <div class="flex-1 border border-gray-200 rounded-lg overflow-hidden">
                                <textarea id="message-input"
                                          class="chat-input w-full px-4 py-3 resize-none focus:outline-none"
                                          placeholder="请输入您的任务描述..." rows="2"></textarea>
                    </div>
                    <button id="send-btn"
                            class="send-btn self-end h-14 w-14 flex items-center justify-center rounded-full bg-gradient-to-r from-blue-500 to-indigo-600 text-white transition-all duration-300 hover:from-blue-600 hover:to-indigo-700">
                        <i class="fas fa-paper-plane text-xl"></i>
                    </button>
                </div>
                <div class="mt-3 flex justify-between text-sm text-gray-500">
                    <div>支持Markdown格式，按Shift+Enter换行</div>
                    <div>AI智能体 v2.1 - 增强版</div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    // =============================================
    // 初始化Markdown渲染器
    // =============================================
    // 使用markdown-it替换marked库
    const md = window.markdownit({
        html: true,
        linkify: true,
        typographer: true,
        highlight: function (code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return `<pre class="hljs"><code>${hljs.highlight(lang, code, true).value}</code></pre>`;
                } catch (__) {
                }
            }
            return `<pre class="hljs"><code>${md.utils.escapeHtml(code)}</code></pre>`;
        }
    }).use(window.markdownitTaskLists);  // 添加任务列表支持

    // 任务进行中状态标志
    let taskInProgress = false;

    // =============================================
    // 会话和消息数据管理
    // =============================================

    // 会话数据结构
    class Session {
        constructor(id, title) {
            this.id = id;
            this.title = title;
            this.createdAt = new Date();
            this.lastActive = new Date();
            this.messages = [];
            this.stepCounter = 0;
            this.taskId = 0;
        }

        addMessage(sender, content, step = 0) {
            const message = {
                id: Date.now(),
                sender,
                content,
                timestamp: new Date(),
                step
            };
            this.messages.push(message);
            this.lastActive = new Date();
            return message;
        }
    }

    // 会话管理器
    class SessionManager {
        constructor() {
            this.sessions = [];
            this.currentSessionId = null;
            this.loadFromLocalStorage();

            // 如果没有任何会话，创建一个默认会话
            if (this.sessions.length === 0) {
                this.createSession("默认会话");
            }

            this.currentSessionId = this.sessions[0].id;
        }

        createSession(title = "新会话") {
            const id = 'session-' + Date.now();
            const session = new Session(id, title);
            this.sessions.push(session);
            this.currentSessionId = id;
            this.saveToLocalStorage();
            return session;
        }

        getCurrentSession() {
            return this.sessions.find(s => s.id === this.currentSessionId);
        }

        switchSession(sessionId) {
            this.currentSessionId = sessionId;
            this.saveToLocalStorage();
            return this.getCurrentSession();
        }

        deleteSession(sessionId) {
            this.sessions = this.sessions.filter(s => s.id !== sessionId);
            if (this.currentSessionId === sessionId) {
                this.currentSessionId = this.sessions.length > 0 ? this.sessions[0].id : null;
            }
            this.saveToLocalStorage();
        }

        updateSessionTitle(sessionId, newTitle) {
            const session = this.sessions.find(s => s.id === sessionId);
            if (session) {
                session.title = newTitle;
                this.saveToLocalStorage();
            }
        }

        saveToLocalStorage() {
            localStorage.setItem('ai-sessions', JSON.stringify({
                sessions: this.sessions,
                currentSessionId: this.currentSessionId
            }));
        }

        loadFromLocalStorage() {
            const data = JSON.parse(localStorage.getItem('ai-sessions'));
            if (data) {
                this.sessions = data.sessions.map(s => {
                    const session = new Session(s.id, s.title);
                    session.createdAt = new Date(s.createdAt);
                    session.lastActive = new Date(s.lastActive);
                    session.messages = s.messages;
                    session.stepCounter = s.stepCounter || 0;
                    session.taskId = s.taskId || 0;
                    return session;
                });
                this.currentSessionId = data.currentSessionId;
            }
        }
    }

    // =============================================
    // SSE服务管理（真实后端连接）
    // =============================================

    class SSEService {
        constructor() {
            this.eventSource = null;
            this.connectionStatus = document.getElementById('connection-status');
            this.statusIndicator = this.connectionStatus.querySelector('.status-indicator');
            this.connect();
        }

        connect() {
            // 真实SSE服务URL
            this.updateConnectionStatus(true);
        }

        // 创建真实的EventSource连接
        createEventSource(message, session, onProgress, onResponse, onError) {
            try {
                // 编码用户消息，确保URL安全
                const encodedMessage = encodeURIComponent(message);
                const url = `http://127.0.0.1:8007/ai/manus/chat?message=${encodedMessage}`;

                // 创建真实SSE连接
                const eventSource = new EventSource(url);

                eventSource.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);

                        // 关键修改：处理 <END> 标签
                        if (data.content && data.content.trim() === "<END>") {
                            // 重置步骤计数器
                            session.stepCounter = 0;

                            // 标记任务结束
                            taskInProgress = false;
                            sendBtn.disabled = false;

                            // 关闭连接
                            eventSource.close();
                            return;
                        }

                        if (data.type === "progress") {
                            onProgress(data.content);
                        } else if (data.type === "response") {
                            session.stepCounter++;
                            onResponse(data.content, session.stepCounter);
                        } else if (data.type === "complete") {
                            onProgress("任务完成");
                            eventSource.close(); // 任务完成后关闭连接
                        } else {
                            console.error("未知事件类型:", data.type);
                        }
                    } catch (parseError) {
                        console.error("事件数据解析失败:", parseError);
                        session.stepCounter++;
                        onResponse(event.data, session.stepCounter);
                    }
                };

                eventSource.onerror = (error) => {
                    // 关键修改：错误时启用发送按钮
                    taskInProgress = false;
                    sendBtn.disabled = false;

                    eventSource.close();
                    this.updateConnectionStatus(false);
                };

                return eventSource;
            } catch (error) {
                // 关键修改：异常时启用发送按钮
                taskInProgress = false;
                sendBtn.disabled = false;

                console.error("创建SSE连接失败:", error);
                onError("无法建立连接");
                return null;
            }
        }

        // 发送消息到SSE服务（真实连接）
        sendMessage(message, session, onProgress, onResponse, onError) {
            const sessionRef = session;

            // 确保关闭任何现有连接
            if (this.eventSource) {
                this.eventSource.close();
            }

            // 创建真实SSE连接
            this.eventSource = this.createEventSource(
                message,
                sessionRef,
                onProgress,
                onResponse,
                onError
            );

            // 返回关闭连接的方法
            return {
                close: () => {
                    if (this.eventSource) {
                        this.eventSource.close();
                    }
                }
            };
        }

        // 更新连接状态
        updateConnectionStatus(connected) {
            if (connected) {
                this.connectionStatus.className = "connection-status connected";
                this.statusIndicator.className = "status-indicator bg-white";
                this.connectionStatus.querySelector('span').textContent = "已连接到SSE服务";
            } else {
                this.connectionStatus.className = "connection-status disconnected";
                this.statusIndicator.className = "status-indicator bg-white";
                this.connectionStatus.querySelector('span').textContent = "SSE服务断开连接";
            }
        }

        // 关闭连接
        close() {
            if (this.eventSource) {
                this.eventSource.close();
                this.eventSource = null;
            }
            this.updateConnectionStatus(false);
        }
    }

    // =============================================
    // 应用主逻辑
    // =============================================

    // DOM元素
    const chatContainer = document.getElementById('chat-container');
    const messageInput = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    const progressBar = document.querySelector('.progress-bar');
    const sessionsList = document.getElementById('sessions-list');
    const newSessionBtn = document.getElementById('new-session-btn');
    const sessionTitleInput = document.getElementById('session-title-input');
    const clearChatBtn = document.getElementById('clear-chat-btn');
    const sidebar = document.getElementById('sidebar');
    const menuToggle = document.getElementById('menu-toggle');

    // 初始化会话管理器和SSE服务
    const sessionManager = new SessionManager();
    const sseService = new SSEService();

    // 当前SSE连接对象
    let currentSSEConnection = null;

    // 渲染会话列表
    function renderSessionsList() {
        sessionsList.innerHTML = '';

        sessionManager.sessions.forEach(session => {
            const isActive = session.id === sessionManager.currentSessionId;
            const sessionElement = document.createElement('div');

            // 格式化时间
            const formatTime = (date) => {
                const now = new Date();
                const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));

                if (diffDays === 0) {
                    return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
                } else if (diffDays === 1) {
                    return '昨天';
                } else {
                    return date.toLocaleDateString();
                }
            };

            sessionElement.className = `session-item ${isActive ? 'active' : ''}`;
            sessionElement.dataset.id = session.id;

            sessionElement.innerHTML = `
                        <div class="session-title">${session.title}</div>
                        <div class="session-time">${formatTime(session.lastActive)}</div>
                        <div class="absolute right-3 top-3 text-gray-500 hover:text-red-400 delete-session">
                            <i class="fas fa-times"></i>
                        </div>
                    `;

            sessionElement.addEventListener('click', () => {
                switchSession(session.id);
            });

            // 删除会话按钮
            const deleteBtn = sessionElement.querySelector('.delete-session');
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                if (sessionManager.sessions.length > 1) {
                    sessionManager.deleteSession(session.id);
                    renderSessionsList();
                } else {
                    alert('至少需要保留一个会话');
                }
            });

            sessionsList.appendChild(sessionElement);
        });
    }

    // 渲染会话内容（消息）
    function renderSessionMessages() {
        chatContainer.innerHTML = '';

        const session = sessionManager.getCurrentSession();
        if (!session) return;

        // 更新会话标题输入框
        sessionTitleInput.value = session.title;

        if (session.messages.length === 0) {
            // 添加初始欢迎消息
            chatContainer.innerHTML = `
<div class="flex justify-start">
    <div class="ai-message p-5">
        <div class="flex items-start space-x-4">
            <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                <i class="fas fa-robot text-white text-lg"></i>
            </div>
            <div class="flex-1">
                <div class="task-indicator">
                    <i class="fas fa-info-circle mr-2"></i>
                    任务智能体已就绪
                </div>
                <div class="prose prose-blue max-w-none message-content">
                    <p>您好！我是您的AI任务智能体，可以帮您自动执行复杂操作流程。您只需下达任务指令，我将自动分解步骤并执行：</p>

                    <p><strong>任务示例：</strong></p>
                    <ul>
                        <li>搜索"北京故宫"的详细信息并整理成报告</li>
                        <li>在Bilibili上搜索"进击的巨人"最新番剧信息</li>
                        <li>创建一个Excel文档，将豆瓣电影Top10写入并保存</li>
                    </ul>

                    <p><strong>我能执行的复杂操作：</strong></p>
                    <ol>
                        <li>多平台信息搜索与整合</li>
                        <li>文件创建与内容生成</li>
                        <li>多步骤任务决策与执行</li>
                    </ol>

                    <p>请在下方的输入框中描述您的任务需求，我将自动分解为可执行步骤！</p>
                </div>
            </div>
        </div>
    </div>
</div>
                    `;
        } else {
            // 渲染所有消息
            session.messages.forEach(message => {
                renderMessageElement(message);
            });
        }

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 渲染单条消息
    function renderMessageElement(message) {
        let messageElement;

        switch (message.sender) {
            case 'user':
                messageElement = createUserMessage(message);
                break;
            case 'ai':
                messageElement = createAIMessage(message);
                break;
            case 'error':
                messageElement = createErrorMessage(message);
                break;
            default:
                return;
        }

        chatContainer.appendChild(messageElement);
        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 创建用户消息元素
    function createUserMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.className = 'flex justify-end mb-6';
        messageElement.innerHTML = `
                <div class="user-message p-5 max-w-[80%]">
                    <div class="flex items-start space-x-4">
                        <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                            <i class="fas fa-user text-white text-lg"></i>
                        </div>
                        <div class="flex-1">
                            <div class="message-content">${renderMarkdown(message.content)}</div>
                        </div>
                    </div>
                </div>
            `;
        return messageElement;
    }

    // 创建AI消息元素
    function createAIMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.className = 'flex justify-start mb-6';

        // 步骤计数器显示
        const stepBadge = message.step > 0 ?
            `<div class="step-badge">步骤 ${message.step}</div>` : '';

        messageElement.innerHTML = `
                <div class="ai-message p-5 max-w-[80%]">
                    ${stepBadge}
                    <div class="flex items-start space-x-4">
                        <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                            <i class="fas fa-robot text-white text-lg"></i>
                        </div>
                        <div class="flex-1">
                            <div class="message-content">${renderMarkdown(message.content)}</div>
                        </div>
                    </div>
                </div>
            `;

        // 添加复制按钮到代码块
        setTimeout(() => {
            messageElement.querySelectorAll('pre').forEach(pre => {
                if (!pre.querySelector('.copy-btn')) {
                    const copyBtn = document.createElement('button');
                    copyBtn.className = 'copy-btn';
                    copyBtn.innerHTML = '<i class="far fa-copy mr-1"></i>复制';
                    copyBtn.onclick = () => {
                        const code = pre.querySelector('code').textContent;
                        navigator.clipboard.writeText(code).then(() => {
                            copyBtn.innerHTML = '<i class="fas fa-check mr-1"></i>已复制';
                            setTimeout(() => {
                                copyBtn.innerHTML = '<i class="far fa-copy mr-1"></i>复制';
                            }, 2000);
                        });
                    };
                    pre.appendChild(copyBtn);
                }
            });
        }, 50);

        return messageElement;
    }

    // 创建错误消息元素
    function createErrorMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.className = 'flex justify-start mb-6';
        messageElement.innerHTML = `
                <div class="error-message p-5 max-w-[80%]">
                    <div class="flex items-start space-x-4">
                        <div class="avatar bg-gradient-to-r from-red-500 to-red-700">
                            <i class="fas fa-exclamation-triangle text-white text-lg"></i>
                        </div>
                        <div class="flex-1">
                            <div class="message-content">
                                <div class="message-label">错误</div>
                                ${renderMarkdown(message.content)}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        return messageElement;
    }

    // 创建正在输入指示器
    function createTypingIndicator() {
        const typingElement = document.createElement('div');
        typingElement.className = 'flex justify-start mb-6';
        typingElement.innerHTML = `
                <div class="ai-message p-5 max-w-[80%]">
                    <div class="flex items-start space-x-4">
                        <div class="avatar bg-gradient-to-r from-blue-500 to-indigo-600">
                            <i class="fas fa-robot text-white text-lg"></i>
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center">
                                <div class="typing-indicator"></div>
                                <div class="typing-indicator ml-1"></div>
                                <div class="typing-indicator ml-1"></div>
                                <span class="ml-2">正在思考中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        return typingElement;
    }

    // 渲染Markdown内容
    function renderMarkdown(content) {
        // 使用markdown-it渲染
        const unsafeHtml = md.render(content || '');

        // 安全过滤
        const safeHtml = DOMPurify.sanitize(unsafeHtml, {
            ADD_ATTR: ['target']  // 允许target属性
        });

        // 添加表格响应式容器
        return safeHtml.replace(/<table>/g, '<div class="table-responsive"><table>')
            .replace(/<\/table>/g, '</table></div>');
    }

    // 切换会话
    function switchSession(sessionId) {
        // 关闭当前SSE连接
        if (currentSSEConnection) {
            currentSSEConnection.close();
            currentSSEConnection = null;
        }

        sessionManager.switchSession(sessionId);
        renderSessionMessages();
        renderSessionsList();
    }

    // 更新进度条
    function updateProgressBar(progressText) {
        // 实现进度条更新逻辑
        // 示例逻辑：progressText可能是 "50%"，设置进度条宽度
        if (progressText.includes('%')) {
            const percent = parseInt(progressText);
            progressBar.style.width = `${percent}%`;
        } else {
            // 如果没有百分比，可以显示文本状态
            progressBar.textContent = progressText;
        }
    }

    // 发送消息
    async function sendMessage() {
        if (taskInProgress) return;

        const message = messageInput.value.trim();
        if (!message) return;

        // 添加用户消息到会话
        const session = sessionManager.getCurrentSession();
        const userMessage = session.addMessage("user", message);
        renderMessageElement(userMessage);

        // 清空输入框
        messageInput.value = "";

        // 禁用发送按钮
        taskInProgress = true;
        sendBtn.disabled = true;
        sendBtn.classList.remove('pulse');

        // 添加AI正在输入指示器
        const typingIndicator = createTypingIndicator();
        chatContainer.appendChild(typingIndicator);
        chatContainer.scrollTop = chatContainer.scrollHeight;

        try {
            currentSSEConnection = sseService.sendMessage(
                message,
                session,
                // 进度更新回调
                (progressText) => {
                    updateProgressBar(progressText);
                },
                // 响应回调
                (responseContent, step) => {
                    // 移除输入指示器
                    if (typingIndicator.parentNode) {
                        chatContainer.removeChild(typingIndicator);
                    }

                    // 添加AI消息
                    const aiMessage = session.addMessage("ai", responseContent, step);
                    renderMessageElement(aiMessage);
                },
                // 错误回调
                (error) => {
                    // 移除输入指示器
                    if (typingIndicator.parentNode) {
                        chatContainer.removeChild(typingIndicator);
                    }

                    // 添加错误消息
                    const errorMessage = session.addMessage("error", error);
                    renderMessageElement(errorMessage);

                    // 重置任务状态
                    taskInProgress = false;
                    sendBtn.disabled = false;
                }
            );
        } catch (error) {
            // 异常时启用发送按钮
            taskInProgress = false;
            sendBtn.disabled = false;

            console.error("发送消息失败:", error);
        }
    }

    // 清空当前会话
    function clearCurrentChat() {
        const session = sessionManager.getCurrentSession();
        if (session) {
            session.messages = [];
            session.stepCounter = 0;
            sessionManager.saveToLocalStorage();
            renderSessionMessages();
        }
    }

    // 初始化应用
    function initApp() {
        // 渲染初始界面
        renderSessionsList();
        renderSessionMessages();

        // 事件监听
        sendBtn.addEventListener('click', sendMessage);

        messageInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!taskInProgress) {
                    sendMessage();
                }
            }
        });

        newSessionBtn.addEventListener('click', () => {
            sessionManager.createSession();
            renderSessionsList();
            renderSessionMessages();
        });

        clearChatBtn.addEventListener('click', clearCurrentChat);

        sessionTitleInput.addEventListener('blur', function () {
            const session = sessionManager.getCurrentSession();
            if (session) {
                session.title = this.value;
                sessionManager.updateSessionTitle(session.id, this.value);
                renderSessionsList();
            }
        });

        sessionTitleInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                this.blur();
            }
        });

        // 移动端菜单切换
        menuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
        });
    }

    // 启动应用
    document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>